package game.breeze.gameserver;

import game.breeze.message.AppMessage;
import game.breeze.message.Message;
import game.breeze.message.codec.AppMessageDecoder;
import game.breeze.message.codec.AppMessageEncoder;
import game.breeze.socket.TcpSocket;
import game.breeze.socket.connection.NetConnection;
import game.breeze.socket.connection.SimpleConnection;
import game.breeze.socket.connection.listener.NetConnectionListener;
import game.breeze.socket.server.listener.NetServerListener;
import game.breeze.socket.util.ByteBuffer;
import game.breeze.socket.util.Utils;

import java.io.IOException;

/**
 * 网络客户
 */
public class NetClient implements Runnable, NetConnectionListener, NetServerListener {
	private SimpleConnection connection;
	private boolean running;

	public NetClient(String host, int port) throws IOException {
		TcpSocket socket = new TcpSocket(host, port);
		connection = new SimpleConnection(socket);
		// connection.setPingTime(1000);
		connection.setMaxBufferSize(0xffff);
		connection.setPingTime(1000);
		connection.setTimeout(5000);
		AppMessageDecoder decoder = new AppMessageDecoder();
		AppMessageEncoder encoder = new AppMessageEncoder();
		connection.setMessageDecoder(decoder);
		connection.setMessageEncoder(encoder);
		connection.addListener(this);
	}

	public void sendMessage(AppMessage msg) {
		if (connection != null)
			connection.sendMessage(msg);
	}

	public NetConnection getNetConnection() {
		return connection;
	}

	public int getPingTime() {
		if (connection != null)
			return connection.getPingTime();
		return 0;
	}

	public void setPingTime(int time) {
		if (connection != null)
			connection.setPingTime(time);
	}

	public boolean isRunning() {
		return running;
	}

	public void start() {
		if (running == true)
			return;
		running = true;
		new Thread(this).start();
	}

	public void stop() {
		running = false;
		if (connection != null)
			connection.close();
	}

	public void run() {
		while (running) {
			if (!connection.isActive()) {
				break;
			}
			while (connection.hasData()) {
				connection.processPeek();
			}
			Utils.sleep(10);
		}

		connection.close();
		connectionClosed(connection);
		connection = null;
		running = false;
	}

	@Override
	public void messageArrived(NetConnection conn, Message msg) {
		AppMessage app = (AppMessage) msg;
		ByteBuffer byteBuffer = app.getBuffer();
		if (app.getType() == AppMessage.MSG_FIGHT) {
			int type = byteBuffer.readInt();
		}
	}

	@Override
	public void connectionOpened(NetConnection connection) {

	}

	@Override
	public void connectionClosed(NetConnection connection) {

	}
}